package com.wangxu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wangxu.blog.dao.mapper.SysUserMapper;
import com.wangxu.blog.dao.pojo.SysUser;
import com.wangxu.blog.service.LoginService;
import com.wangxu.blog.service.SysUserService;
import com.wangxu.blog.vo.ErrorCode;
import com.wangxu.blog.vo.LoginUserVo;
import com.wangxu.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private LoginService loginService;
    @Override
    public SysUser findUserById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser == null){
            sysUser = new SysUser();
            sysUser.setNickname("旭哥学java");
        }
        return sysUser;
    }

    @Override
    public SysUser findUser(String account, String password) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser :: getAccount,account); //设置查询条件
        wrapper.eq(SysUser :: getPassword,password);
        wrapper.select(SysUser :: getAccount,SysUser :: getId, SysUser :: getAvatar, SysUser :: getNickname); //设置查询返回的字段值
        wrapper.last("limit 1");
        return sysUserMapper.selectOne(wrapper);//查询一条数据
    }

    @Override
    public Result findUserByToken(String token) {
        /*
        1、token合法性校验
            是否为空  解析是否成功 redis是否存在
        2、如果校验失败，返回错误信息
        3、如果成功，返回对应的结果 LoginUserVo
         */

        SysUser sysUser =  loginService.checkToken(token);
        if (sysUser == null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(sysUser.getId());
        loginUserVo.setAccount(sysUser.getAccount());
        loginUserVo.setNickname(sysUser.getNickname());
        loginUserVo.setAvatar(sysUser.getAvatar());
        return Result.success(loginUserVo);
    }

    @Override
    public SysUser findUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,account);
        wrapper.last("limit 1");
        return sysUserMapper.selectOne(wrapper);
    }

    @Override
    public void save(SysUser sysUser) {
        //保存用户  id会自动生成
        sysUserMapper.insert(sysUser);
    }


}
